<?PHP
  class DataType{
    private $id          = -1;
    private $displayName = "";
    private $dataName    = "";
    private $description = "";
    private $fields      = array();
    private $validators  = null;

    public function __construct($id){
      $this->id = $id;
      $id  = $GLOBALS['db']->EscapeString($id);
      if($obj = $GLOBALS['db']->ReadRow("SELECT * FROM {'dbprefix'}datatypes WHERE id='".$id."'")){
        $this->displayName = $obj->displayName;
        $this->dataName    = $obj->dataName;
        $this->description = $obj->description;
      }
    }

    public function getFields(){
      if(sizeOf($this->fields) == 0){
        $this->fields = DataField::getByDataType($this);
      }
      return $this->fields;
    }

    public function getID(){
      return $this->id;
    }

    public function getInsertStatement($values, $ignoreColumns = array()){
      return "INSERT INTO {'dbprefix'}".$this->dataName." (".$this->getCommaSeparatedColumnNames($ignoreColumns).") VALUES (".$this->commaSepearate($values).");";
    }

    private function getCommaSeparatedColumnNames($ignoreColumns){
      $res = "";
      foreach($this->getFields() as $field){
        if(!is_array($ignoreColumns) || !in_array($field->getDataName(),$ignoreColumns)){
          $res .= $field->getDataName().",";
        }
      }
      if(strlen($res) > 0){
        $res = substr($res,0,-1);
      }
      return $res;
    }

    private function commaSepearate($values){
      $res = "";
      foreach($values as $value){
        $res .= $value.",";
      }
      if(strlen($res) > 0){
        $res = substr($res,0,-1);
      }
      return $res;
    }

    private function getValidators(){
      if($this->validators == null){
        $this->validators = DataTypeValidator::getByDataType($this);
      }
      return $this->validators;
    }

    public function validate($params){
      $res = true;
      foreach($this->getValidators() as $validator){
        $res = $validator->validate($params) && $res;
      }
      return $res;
    }

    public function getValidatiingErrors(){
      $res = array();
      foreach($this->getValidators() as $validator){
        $message = $validator->getErrorMessage();
        if($message != ""){
          $res[] = $message;
        }
      }
      return $res;
    }


}
?>